package com.db.javaschool.kislros;

import static org.junit.Assert.*;

import org.junit.Test;

public class TinyHastableTest {

	@Test
	public void testConstructor() {
		TinyHastable sh = new TinyHastable(10, -1, -1);
		assertEquals(sh.get(0), -1);
		assertEquals(sh.get(10), -1);
		assertEquals(sh.size(), 0);
		try {
			sh = new TinyHastable(-1);
			fail("Created table of negative capatity.");
		} catch (IllegalArgumentException e) {
			try {
				sh = new TinyHastable(0);
				fail("Created table of zero capatity.");
			} catch (IllegalArgumentException e1) {return;}
		}
	}

	@Test
	public void testMain() {
		System.setProperty(TinyHastable.PRINT_NEAREST_PRIME_TIME, "true");
		TinyHastable.main(new String[]{});
		System.setProperty(TinyHastable.PRINT_NEAREST_PRIME_TIME, "false");
	}
	
	@Test
	public void testGet() {
		TinyHastable sh = new TinyHastable(10, -1, -1);
		sh.put(1, 42);
		sh.put(2, 43);
		sh.put(3, 44);
		assertEquals(sh.get(1), 42);
		assertEquals(sh.get(2), 43);
		assertEquals(sh.get(3), 44);
		assertEquals(sh.get(4), -1);
	}

	@Test
	public void testPutNull() {
		TinyHastable sh = new TinyHastable(10, -1, -1);
		sh.put(1, 42);
		sh.put(-1, 666);
		assertEquals(sh.get(1), 42);
		assertEquals(sh.get(-1), -1);
	}

	@Test
	public void testDifferentDefaults() {
		TinyHastable sh = new TinyHastable(10, -2, -2);
		assertEquals(sh.get(1), -2);
		sh.put(1, 42);
		sh.put(2, 43);
		sh.put(3, 44);
		assertEquals(sh.get(1), 42);
		assertEquals(sh.get(2), 43);
		assertEquals(sh.get(3), 44);
		assertEquals(sh.get(4), -2);
		assertEquals(sh.get(-2), -2);
	}

	@Test
	public void testPutOverflow() {
		TinyHastable sh = new TinyHastable(10, -1, -1);
		try {
			for (int i = 0; i < 100; ++i)
				sh.put(i, 42);
		} catch (IndexOutOfBoundsException e) {
			return;
		}
		fail("Failed in not throwing exception on overflow");
	}

	@Test
	public void testGetWithCollisions() {
		TinyHastable sh = new TinyHastable(10, -1, -1);
		sh.put(1, 42);
		sh.put(12, 43);
		sh.put(23, 44);
		assertEquals(sh.get(1), 42);
		assertEquals(sh.get(12), 43);
		assertEquals(sh.get(23), 44);
		assertEquals(sh.get(34), -1);
		assertEquals(sh.get(2), -1);
	}

	@Test
	public void testClear() {
		TinyHastable sh = new TinyHastable(10, -1, -1);
		sh.put(1, 42);
		sh.put(12, 43);
		sh.put(24, 44);
		sh.clear();
		assertEquals(sh.get(1), -1);
		assertEquals(sh.get(12), -1);
		assertEquals(sh.get(23), -1);
		assertEquals(sh.get(24), -1);
	}
	
	@Test
	public void testSize() {
		TinyHastable sh = new TinyHastable(10, -1, -1);
		assertEquals(sh.size(), 0);
		sh.put(1, 42);
		assertEquals(sh.size(), 1);
		sh.put(12, 43);
		assertEquals(sh.size(), 2);
		sh.put(24, 44);
		assertEquals(sh.size(), 3);
		sh.clear();
		assertEquals(sh.size(), 0);
	}
}
